<?php
/**
 * 码上点餐
 *
 * 作者:迷失卍国度
 *
 * qq : 15595755
 */
defined('IN_IA') or exit('Access Denied');

include "plugin/feyin/HttpClient.class.php";
include "templateMessage.php";
define('FEYIN_HOST', 'my.feyin.net');
define('FEYIN_PORT', 80);
define('FEIE_IP', 'dzp.feieyun.com');
define('FEIE_PORT', 80);
define('FEIE_HOSTNAME', '/FeieServer');

class weisrc_dishModuleWxapp extends WeModuleWxapp
{
    //模块标识
    public $modulename = 'weisrc_dish';
    public $cur_tpl = 'style1';
    public $cur_mobile_path = '';
    public $cur_res = '';
    public $cur_version = 1;

    public $member_code = '';
    public $feyin_key = '';
    public $device_no = '';

    public $msg_status_success = 1;
    public $msg_status_bad = 0;
    public $_debug = '1'; //default:0
    public $_weixin = '1'; //default:1

    public $_appid = '';
    public $_appsecret = '';
    public $_accountlevel = '';
    public $_account = '';

    public $_weid = '';
    public $_fromuser = '';
    public $_nickname = '';
    public $_headimgurl = '';

    public $_auth2_openid = '';
    public $_auth2_nickname = '';
    public $_auth2_headimgurl = '';
    public $_auth2_key = 'bHYzNjAubmV0LmNu';
    public $_lat = '';
    public $_lng = '';
    public $table_area = 'weisrc_dish_area';
    public $table_blacklist = 'weisrc_dish_blacklist';
    public $table_cart = 'weisrc_dish_cart';
    public $table_category = 'weisrc_dish_category';
    public $table_email_setting = 'weisrc_dish_email_setting';
    public $table_goods = 'weisrc_dish_goods';
    public $table_intelligent = 'weisrc_dish_intelligent';
    public $table_nave = 'weisrc_dish_nave';
    public $table_order = 'weisrc_dish_order';
    public $table_order_goods = 'weisrc_dish_order_goods';
    public $table_print_order = 'weisrc_dish_print_order';
    public $table_print_setting = 'weisrc_dish_print_setting';
    public $table_reply = 'weisrc_dish_reply';
    public $table_setting = 'weisrc_dish_setting';
    public $table_sms_checkcode = 'weisrc_dish_sms_checkcode';
    public $table_sms_setting = 'weisrc_dish_sms_setting';
    public $table_store_setting = 'weisrc_dish_store_setting';
    public $table_mealtime = 'weisrc_dish_mealtime';
    public $table_stores = 'weisrc_dish_stores';
    public $table_coupon = 'weisrc_dish_coupon';
    public $table_sncode = 'weisrc_dish_sncode';
    public $table_collection = 'weisrc_dish_collection';
    public $table_type = 'weisrc_dish_type';
    public $table_ad = 'weisrc_dish_ad';
    public $table_template = "weisrc_dish_template";
    public $table_account = "weisrc_dish_account";
    public $table_queue_setting = "weisrc_dish_queue_setting";
    public $table_queue_order = "weisrc_dish_queue_order";
    public $table_tablezones = "weisrc_dish_tablezones";
    public $table_tables = "weisrc_dish_tables";
    public $table_tables_order = "weisrc_dish_tables_order";
    public $table_reservation = "weisrc_dish_reservation";
    public $table_fans = "weisrc_dish_fans";
    public $table_feedback = "weisrc_dish_feedback";
    public $table_businesslog = "weisrc_dish_businesslog";
    public $table_tpl_log = "weisrc_dish_tpl_log";
    public $table_savewine_log = "weisrc_dish_savewine_log";
    public $table_commission = "weisrc_dish_commission";
    public $table_service_log = "weisrc_dish_service_log";
    public $table_print_label = "weisrc_dish_print_label";
    public $table_order_log = "weisrc_dish_order_log";
    public $table_dispatcharea = "weisrc_dish_dispatcharea";
    public $table_deliveryarea = "weisrc_dish_deliveryarea";
    public $table_recharge = "weisrc_dish_recharge";
    public $table_useraddress = "weisrc_dish_useraddress";
    public $serverip = '';

    public $global_sid = 0;
    public $logo = '';
    public $more_store_psize = 10;
    public $_isdebug = 0;

    function __construct()
    {
        global $_W, $_GPC;
        if ($this->_isdebug == 1) {
            $this->_fromuser = 'debug';
        } else {
            $this->_fromuser = $_W['openid'];
        }

        $host = $_SERVER['HTTP_HOST'];
        $this->_weid = $_W['uniacid'];
        $account = $_W['account'];
        $this->_auth2_openid = 'auth2_openid_' . $_W['uniacid'];
        $this->_auth2_nickname = 'auth2_nickname_' . $_W['uniacid'];
        $this->_auth2_headimgurl = 'auth2_headimgurl_' . $_W['uniacid'];

        $this->_lat = 'lat_' . $this->_weid;
        $this->_lng = 'lng_' . $this->_weid;

        $this->_appid = '';
        $this->_appsecret = '';
        $this->_accountlevel = $account['level']; //是否为高级号

        if (isset($_COOKIE[$this->_auth2_openid])) {
            $this->_fromuser = $_COOKIE[$this->_auth2_openid];
        }

        if (isset($_COOKIE['global_sid_' . $_W['uniacid']])) {
            $this->global_sid = $_COOKIE['global_sid_' . $_W['uniacid']];
        }

        if ($this->_accountlevel < 4) {
            $setting = uni_setting($this->_weid);
            $oauth = $setting['oauth'];
            if (!empty($oauth) && !empty($oauth['account'])) {
                $this->_account = account_fetch($oauth['account']);
                $this->_appid = $this->_account['key'];
                $this->_appsecret = $this->_account['secret'];
            }
        } else {
            $this->_appid = $_W['account']['key'];
            $this->_appsecret = $_W['account']['secret'];
        }

        $logo = pdo_fetch("SELECT site_logo FROM " . tablename($this->table_setting) . " WHERE weid = :weid", array
        (':weid' => $this->_weid));
        if (empty($logo['site_logo'])) {
            $this->logo = '../addons/weisrc_dish/template/images/logo.png';
        } else {
            $this->logo = tomedia($logo['site_logo']);
        }

        $template = pdo_fetch("SELECT * FROM " . tablename($this->table_template) . " WHERE weid = :weid", array(':weid' => $this->_weid));
        if (!empty($template)) {
            $this->cur_tpl = $template['template_name'];
        }
        $this->cur_res = RES . '/mobile/' . $this->cur_tpl;
        $this->cur_mobile_path = RES . '/mobile/' . $this->cur_tpl;
    }

    public function doPageIndex()
    {
        global $_W, $_GPC;
        $setting = pdo_fetch("SELECT * FROM " . tablename('weisrc_dish_wxappsetting') . " where weid = :weid LIMIT 1", array(':weid' => $this->_weid));
        header("Content-type: application/json; charset=utf-8");
        return $this->result(0, '', array('appweid' => $setting['wxappweid'], 'bartitle' => $setting['bartitle'],
            'siteroot' => $_W['siteroot'], 'storeid' => $setting['storeid']));
    }

    public function doPageList()
    {
        global $_W, $_GPC;
        $setting = pdo_fetch("SELECT * FROM " . tablename('weisrc_dish_wxappsetting') . " where weid = :weid LIMIT 1", array(':weid' => $this->_weid));

        $id = intval($_GPC['id']);
        $data = pdo_fetch("SELECT * FROM " . tablename($this->table_tables) . " where id=:id LIMIT 1", array(':id' => $id));

        file_put_contents(IA_ROOT . "/addons/weisrc_dish/wxtables.log", var_export($_GPC, true) . PHP_EOL,
            FILE_APPEND);

        header("Content-type: application/json; charset=utf-8");
        return $this->result(0, '', array('appweid' => $setting['wxappweid'], 'bartitle' => $setting['bartitle'],
            'siteroot' => $_W['siteroot'], 'storeid' => $data['storeid'], 'tablesid' => $data['id'], 'id' =>
                $id, 'weid' => $this->_weid));
    }

    public function doPageGetMoreStore()
    {
        global $_GPC, $_W;
    }

    public function doPagePay()
    {
        global $_GPC, $_W;
        $login_success = $this->checkLogin();
        if (is_error($login_success)) {
            return $this->result($login_success['errno'], $login_success['message']);
        }

        //获取订单号，保证在业务模块中唯一即可
        $orderid = intval($_GPC['orderid']);
        $myorder = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE id=:id LIMIT 1", array(':id' => $orderid));
        //构造支付参数

        $order = array(
            'tid' => $orderid,
            'user' => $_W['openid'], //用户OPENID
            'fee' => floatval($myorder['totalprice']), //金额
            'title' => '码上点餐订单',
        );

        //生成支付参数，返回给小程序端
        $pay_params = $this->pay($order);
        if (is_error($pay_params)) {
            file_put_contents(IA_ROOT . "/addons/weisrc_dish/wxpay.log", var_export($pay_params, true) . PHP_EOL,
                FILE_APPEND);
            return $this->result(1, '支付失败:' . $pay_params['message']);
        }
        return $this->result(0, '', $pay_params);
    }

    private function checkLogin()
    {
        global $_W;

//        if (empty($_W['fans'])) {
        if (empty($this->_fromuser)) {
            return error(1, '请先登录');
        }
        return true;
    }

    public function getSetting()
    {
        global $_W, $_GPC;
        $setting = pdo_fetch("SELECT * FROM " . tablename($this->table_setting) . " where weid = :weid LIMIT 1", array(':weid' => $this->_weid));
        return $setting;
    }

    public function doPagePayResult(){
        global $_W, $_GPC;

        $orderid = intval($_GPC['orderid']);
        $paylog = pdo_fetch("SELECT * FROM ". tablename("core_paylog")." WHERE type=:type AND tid=:tid AND module=:module",array(':type'=>'wxapp',':tid'=>$orderid,':module'=>$this->modulename));
        if(empty($paylog) || $paylog['status'] != 1){
            return $this->result(1, '支付失败，请重试!');
        }
        $wxsetting = pdo_fetch("SELECT * FROM " . tablename('weisrc_dish_wxappsetting') . " where weid = :weid LIMIT 1", array(':weid' => $this->_weid));
        $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE id=:id LIMIT 1", array(':id' => $orderid));
        $storeid = $order['storeid'];
        $store = pdo_fetch("SELECT * FROM " . tablename($this->table_stores) . " WHERE id=:id LIMIT 1", array(':id' => $storeid));

        $tag = iunserializer($paylog['tag']);
        $data['transid'] = $tag['transaction_id'];
        $data['paytype'] = 2;
        $data['ispay'] = 1;
        $data['paytime'] = TIMESTAMP;
        if ($store['is_auto_confirm'] == 1 && $order['status'] == 0) {
            $data['status'] = 1;
        }

        $url  = $_W['siteroot'] . "app/index.php?i=" .$wxsetting['wxappweid']. "&c=entry&do=MiniPayNotify&m=weisrc_dish&plid=".$paylog['plid']."&orderid=" . $orderid;
        file_get_contents($url);

        return $this->result(0, '', array('siteroot'=>$_W['siteroot'],'appweid' => $wxsetting['wxappweid'],'plid'=>$paylog['plid']));
    }
}